<?php

namespace backend\controllers;

use Yii;
use backend\models\CustomerContact;
use backend\models\CustomerContactSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use kartik\grid\EditableColumnAction;
use yii\helpers\ArrayHelper;
use backend\models\UploadFormDjr;

/**
 * CustomerContactController implements the CRUD actions for CustomerContact model.
 */
class CustomerContactController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => [],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actions()
    {
        return ArrayHelper::merge(parent::actions(), [
            'edit' => [
                'class' => EditableColumnAction::className(),     // action class name
                'modelClass' => CustomerContact::className(),                // the update model class
                'outputValue' => function ($model, $attribute, $key, $index) {
                    $fmt = Yii::$app->formatter;
                    $value = $model->$attribute;                 // your attribute value
//                    if ($attribute === 'buy_amount') {           // selective validation by attribute
//                        return $fmt->asDecimal($value, 2);       // return formatted value if desired
//                    } elseif ($attribute === 'publish_date') {   // selective validation by attribute
//                        return $fmt->asDate($value, 'php:Y-m-d');// return formatted value if desired
//                    }
                    return '';                                   // empty is same as $value
                },
                'outputMessage' => function ($model, $attribute, $key, $index) {
                    return '';                                  // any custom error after model save
                },
                // 'showModelErrors' => true,                     // show model errors after save
                // 'errorOptions' => ['header' => '']             // error summary HTML options
                // 'postOnly' => true,
                'ajaxOnly' => true,
                // 'findModel' => function($id, $action) {},
                // 'checkAccess' => function($action, $model) {}
            ]
        ]);
    }

    /**
     * Lists all CustomerContact models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new CustomerContactSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single CustomerContact model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new CustomerContact model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new CustomerContact();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing CustomerContact model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {

            $model->validateMobileUnique($model->mobile);
            $model->owner=Yii::$app->user->id;
            if ($_FILES['CustomerContact']['name']['image']) {
                $model_upload = new UploadFormDjr();
                $model_upload->scenario = 'default';
//                $model->image = $model_upload->uploadFile($model, 'uploads', 'image', false);
                $model->image = $model_upload->uploadImage($model, 'uploads', 'image', false);
            }else{
                unset($model->image);
            }
            if ($model->save()) {
                return $this->redirect(['customer/update', 'id' => $model->customer_id, '#' => 'contact-info']);
//                return $this->redirect(Yii::$app->request->referrer);
            } else {
                Yii::$app->session->setFlash('danger', serialize($model->getFirstErrors()));
                return $this->redirect(Yii::$app->request->referrer);
            }

        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing CustomerContact model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $model = $this->findModel($id);
        $customer_id = $model->customer_id;
        $model->delete();
        return $this->redirect(['customer/update', 'id' => $model->customer_id, '#' => 'contact-info']);
    }

    /**
     * Finds the CustomerContact model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return CustomerContact the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = CustomerContact::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
